<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use GuzzleHttp\Psr7\Header;
use think\Db;
use think\Exception;
/**
 * 代理商管理
 *
 * @icon fa fa-circle-o
 */
class Agent extends Backend
{

    /**
     * Agent模型对象
     * @var \app\admin\model\Agent
     */
    protected $model = null;
    protected $noNeedLogin = ['index2', 'add2', 'edit2'];
    protected $grouplist = [];
    protected $groupdata = [];
    protected $agentself = null; //账号对应的Agent

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Agent;

        if ($this->auth->id <= 2) {
            //admin或DFGAME_Admin才使用树形控件，其他只显示他的下级
            $groupList = collection($this->model->with(['admin', 'user'])->select())->toArray();

            Tree::instance()->init($groupList);

            $pid = 0;
            $a = \app\admin\model\Agent::where('admin_id', $this->auth->id)->find();
            if ($a) {
                $pid = $a->pid;
            }
            $groupList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($pid));

            $groupName = [];
            foreach ($groupList as $k => $v) {
                $groupName[$v['id']] = $v['name'];
            }

            $this->grouplist = $groupList;
            $this->groupdata = $groupName;

            $this->assignconfig("admin", ['id' => $this->auth->id, 'group_ids' => $this->auth->getGroupIds()]);
        }

        $this->agentself = \app\admin\model\Agent::where('admin_id', $this->auth->id)->find();
        if ($this->agentself) {
            $ss = $this->agentself->toArray();
            $this->view->assign('agentself', $ss);
        }


        $this->view->assign('groupdata', $this->groupdata);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        if ($this->auth->id <= 2) {
            $url = "http://".$_SERVER['HTTP_HOST']."/admin/agent/index2";//?ref=addtabs
            header("Location: {$url}");
            exit();
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['admin', 'user'])
                ->where($where)
                ->where('pid', $this->agentself->id)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {


            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index2()
    {
        if ($this->request->isAjax()) {
            $list = $this->grouplist;
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');

            if ($params) {
                $dduser = \app\admin\model\dd\User::get(intval($params['dd_user_id']));
                if (!$dduser) {
                    $this->error(__('需绑定用户'));
                }
                $params['name'] = $dduser->nickname;
                $fagent = \app\admin\model\Agent::get(intval($params['pid']));
                if (!$fagent) {
                    $this->error(__('无效的父ID'));
                }
                if ($fagent->level >= 10 ) {
                    $this->error(__('代理已超过10级，请重新选择上级！'));
                }
                $params['level'] = $fagent->level + 1;

                $this->model->create($params);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    //http://bjls.test/admin/agent/add2
    public function add2()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');

            if ($params) {
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    //http://bjls.test/admin/agent/edit2
    public function edit2($ids = null)
    {
        $row = $this->model->with(['admin', 'user'])->where('agent.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');

            // 父节点不能是它自身的子节点或自己本身
            if (in_array($params['pid'], Tree::instance()->getChildrenIds($row->id, true))) {
                $this->error(__('The parent group can not be its own child or itself'));
            }

            $parentmodel = \app\admin\model\Agent::get($params['pid']);
            if (!$parentmodel) {
                $this->error(__('The parent group can not found'));
            }

            if ($params) {
                Db::startTrans();
                try {
                    $row->save($params);
//                    $children_auth_groups = \app\admin\model\Agent::all(['id' => ['in', implode(',', (Tree::instance()->getChildrenIds($row->id)))]]);
//                    $childparams = [];
//                    foreach ($children_auth_groups as $key => $children_auth_group) {
//                        $childparams[$key]['id'] = $children_auth_group->id;
//                    }
//                    \app\admin\model\Agent::saveAll($childparams);
                    Db::commit();
                    $this->success();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error();
            return;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除--无批量删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $num = $this->model->where('pid', $ids)->count();//子id的数量

            if ($num > 0) {
                $this->error(__('请先删除子供应商！'));
            }
            $count = $this->model->where('id', $ids)->delete();
            if ($count) {
                $this->success();
            }
        }
        $this->error();
    }

}
